package com.zmn.oms.third.tc58.dto;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zmn.common.utils.string.StringUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;
import java.util.regex.Pattern;

/**
 * 类描述：
 *
 * @author LiangHailong
 * @since 2022-04-13 10:39
 */
@Slf4j
public class Tc58ExtOuterData {
    private final int receiveChannelCompleteFlag = 0x00000100;

    @Getter
    @Setter
    private String bUserId;
    /**
     * 标记
     */
    private Integer flag;

    /**
     * 是否收到过渠道的订单完成通知
     * @return
     */
    public boolean receivedChannelCompleteNotice() {
        int flagValue = flag != null ? flag.intValue() : 0;
        return (flagValue & receiveChannelCompleteFlag) == receiveChannelCompleteFlag ;
    }

    /**
     * 标记收到了渠道的订单完成通知
     */
    public void flagChannelCompleteNotice() {
        int flagValue = flag != null ? flag.intValue() : 0;
        this.flag = (flagValue | receiveChannelCompleteFlag);
    }

    /**
     * 解析存储在 oms_order_extend 表中的 extOuterData 字段
     * @param extOuterData
     * @return
     */
    public static Tc58ExtOuterData fromExtOuterData(String extOuterData) {
        Tc58ExtOuterData tc58ExtOuterData = new Tc58ExtOuterData();

        if (StringUtil.isNotBlank(extOuterData)) {
            extOuterData = extOuterData.trim();

            if (Pattern.matches("^\\w+$", extOuterData)) {
                tc58ExtOuterData.bUserId = extOuterData;
                return tc58ExtOuterData;
            }

            try {
                JSONObject jsonObject = JSON.parseObject(extOuterData);

                tc58ExtOuterData.bUserId = jsonObject.getString("bUserId");
                tc58ExtOuterData.flag = Optional.ofNullable(jsonObject.getInteger("flag")).orElse(0);

                return tc58ExtOuterData;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

        tc58ExtOuterData.bUserId = extOuterData;

        return tc58ExtOuterData;
    }

    @Override
    public String toString() {
        return String.format(
                "{\"bUserId\":\"%s\",\"flag\":%d}",
                bUserId != null ? bUserId : "",
                flag != null ? flag : 0
        );
    }

}
